var CountIntervals = function() {
  this.data = [];
  this.binarySearch = (target, nums) => {
    const n = nums.length;
    let left = 0, right = n - 1, ans = n;
    while (left <= right) {
        let mid = ((right - left) >> 1) + left;
        if (target <= Math.abs(nums[mid])) {
            ans = mid;
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return ans;
  }
};

/** 
* @param {number} left 
* @param {number} right
* @return {void}
*/
CountIntervals.prototype.add = function(left, right) {
  // console.log(this.data);
  const lPos = this.binarySearch(left, this.data);
  const rPos = this.binarySearch(right, this.data);
  // console.log(lPos, rPos);
  if (lPos === rPos && (lPos === 0 || rPos === this.data.length)) {
    this.data.splice(lPos, 0, -left, right);
  }
  else {
      const lFlag = this.data[lPos] < 0 ;
      const rFlag = rPos === this.data.length || this.data[rPos] < 0;
      if(lFlag && rFlag) {
          this.data = [...this.data.slice(0, lPos), -left, right, ...this.data.slice(rPos)];
      } else if(lFlag && !rFlag) {
          this.data = [...this.data.slice(0, lPos), -left, ...this.data.slice(rPos)];
      } else if(!lFlag && rFlag) {
        this.data = [...this.data.slice(0, lPos), right,...this.data.slice(rPos)];
      } else {
        this.data = [...this.data.slice(0, lPos), ...this.data.slice(rPos)];
      }
  }
};

/**
* @return {number}
*/
CountIntervals.prototype.count = function() {
  console.log(this.data);
  return this.data.length ? this.data.reduce((a, b, i) => a + b + i % 2 + ((b === -this.data[i - 1]) && b < 0 ? -1 : 0)) : 0;
};

/**
* Your CountIntervals object will be instantiated and called as such:
* var obj = new CountIntervals()
* obj.add(left,right)
* var param_2 = obj.count()
*/

var obj = new CountIntervals()
obj.add(33, 49)
obj.add(43, 47)
obj.add(37, 37);
obj.add(26, 38)
obj.add(11, 11);
console.log(obj.count());

// 超时， 应该用线段树做